﻿using UnityEngine;
using System.Collections;
using ProtoBuf.Message;
using System.Collections.Generic;
#if !NAKED
using supersdkUnity;
#endif
namespace Login
{
    public class LoginPlayerLogin : Fsm.FsmStateMonoBase<LoginState>
    {
        LoginManager manager = null;
        public LoginPlayerLogin(LoginState state, LoginManager ctrl) : base(state, ctrl) { manager = ctrl; }
        public override void Enter()
        {
            //base.Enter();
            PlayerLogin();
        }

        void PlayerLogin()
        {
            CSPlayerLogin msg = new CSPlayerLogin();

            NetAPI.SendHttp(OpDefine.CSPlayerLogin, msg, PlayerLoginCallBack);

            Debug.Log("playerInit");
        }


        SCPlayerLogin playerLogin;
        void PlayerLoginCallBack(NetWork.Packets.Packet packet, bool bSuccess)
        {
            if (bSuccess)
            {
                playerLogin = packet.kBody as SCPlayerLogin;
                if (playerLogin != null)
                {
                    StaticData.playerData.createRoleTime = playerLogin.playerCreateTime.ToString();

                    Debug.Log("创建人物成功，开始装逼之旅吧");

                    CSEquipmentTreasureList msgET = new CSEquipmentTreasureList();
                    NetAPI.SendHttp(OpDefine.CSEquipmentTreasureList, msgET, ETListCallBack);
                 
                    
                }
            }
            else
            {
                DoFail("CSPlayerLogin",OpDefine.CSPlayerLogin);
            }
            
        }
        SCEquipmentTreasureList EquipmentTreasureList;
        void ETListCallBack(NetWork.Packets.Packet packet, bool bSuccess)
        {
            if (bSuccess)
            {
                //SCEquipmentTreasureList msg = packet.kBody as SCEquipmentTreasureList;
                EquipmentTreasureList = packet.kBody as SCEquipmentTreasureList;
                CSWarriorList wmsg = new CSWarriorList();
                NetAPI.SendHttp(OpDefine.CSWarriorList, wmsg, WListCallBack);

            }
            else
            {
                DoFail("CSEquipmentTreasureList", OpDefine.CSEquipmentTreasureList);
            }
        }
        SCWarriorList warriorList;
        void WListCallBack(NetWork.Packets.Packet packet, bool bSuccess)
        {
            if (bSuccess)
            {
                warriorList = packet.kBody as SCWarriorList;

                CSItemList imsg = new CSItemList();
                NetAPI.SendHttp(OpDefine.CSItemList, imsg, IListCallBack);
            }
            else
            {
                DoFail("CSWarriorList", OpDefine.CSWarriorList);
            }
        }
        SCItemList itemList;
        void IListCallBack(NetWork.Packets.Packet packet, bool bSuccess)
        {
            if (bSuccess)
            {
                itemList = packet.kBody as SCItemList;

                CSGemAndCookingList gcmsg = new CSGemAndCookingList();
                NetAPI.SendHttp(OpDefine.CSGemAndCookingList, gcmsg, GCListCallback);
            }
            else
            {
                DoFail("CSItemList", OpDefine.CSItemList);
            }
        }
        SCGemAndCookingList cookingList;
        void GCListCallback(NetWork.Packets.Packet packet, bool bSuccess)
        {
            if (bSuccess)
            {
                cookingList = packet.kBody as SCGemAndCookingList;

                CSFragmentList imsg = new CSFragmentList();
                NetAPI.SendHttp(OpDefine.CSFragmentList, imsg, FListCallBack);
            }
            else
            {
                DoFail("CSGemAndCookingList", OpDefine.CSGemAndCookingList);
            }
        }
        SCFragmentList fragmentList;
        void FListCallBack(NetWork.Packets.Packet packet, bool bSuccess)
        {
            if (bSuccess)
            {
                fragmentList = packet.kBody as SCFragmentList;

                CSTitleList msgTitleList = new CSTitleList();
                NetAPI.SendHttp(OpDefine.CSTitleList, msgTitleList, TitleListCallback);
            }
            else
            {
                DoFail("CSFragmentList", OpDefine.CSFragmentList);
            }
        }
        SCTitleList titleMsg;
        void TitleListCallback(NetWork.Packets.Packet packet, bool bSuccess)
        {
            if (bSuccess)
            {
                titleMsg = packet.kBody as SCTitleList;

                CSFormationList fmsg = new CSFormationList();
                NetAPI.SendHttp(OpDefine.CSFormationList, fmsg, ForMationCallBack);
            }
            else
            {
                DoFail("CSTitleList", OpDefine.CSTitleList);
            }
        }


        SCFormationList formationList;
        void ForMationCallBack(NetWork.Packets.Packet packet, bool bSuccess)
        {
            if (bSuccess)
            {
                formationList = packet.kBody as SCFormationList;

                //CSConvertGiftCode fmsg = new CSConvertGiftCode();
                //NetAPI.SendHttp(OpDefine.CSConvertGiftCode, fmsg, CCallBack);
                CSPetList fmsg = new CSPetList();
                NetAPI.SendHttp(OpDefine.CSPetList, fmsg, GPListCallback);
            }
            else
            {
                DoFail("CSFormationList", OpDefine.CSFormationList);
            }
        }


        SCPetList petList;
        void GPListCallback(NetWork.Packets.Packet packet, bool bSuccess)
        {
            if (bSuccess)
            {
                petList = packet.kBody as SCPetList;

                CSChangeNameTimes fmsg = new CSChangeNameTimes();
                NetAPI.SendHttp(OpDefine.CSChangeNameTimes, fmsg, ChangeCallBack);
            }
            else
            {
                DoFail("CSPetList", OpDefine.CSPetList);
            }
        }

        //SCConvertGiftCode convertGiftCode;
        void CCallBack(NetWork.Packets.Packet packet, bool bSuccess)
        {
            //convertGiftCode = packet.kBody as SCConvertGiftCode;

            //CSChangeNameTimes fmsg = new CSChangeNameTimes();
            //NetAPI.SendHttp(OpDefine.CSChangeNameTimes, fmsg, ChangeCallBack);
        }
        SCChangeNameTimes changeNameTimes;
        void ChangeCallBack(NetWork.Packets.Packet packet, bool bSuccess)
        {
            if (bSuccess)
            {
                changeNameTimes = packet.kBody as SCChangeNameTimes;              
                
                //StaticData.InitPlayerData(msg);
                StaticData.InitPlayerData(playerLogin, EquipmentTreasureList, warriorList, itemList, fragmentList, formationList, changeNameTimes, cookingList,petList);

                StaticData.playerData.UpdatePlayerTitle(titleMsg.curTitle, titleMsg.titleList);
                if (GameConfig.Instance.platform == 2)
                {
#if UNITY_ANDROID
                    //登陆成功后必须调用悬浮按钮和提交数据函数，否则有些渠道审核不通过
                    if (SuperSDKUnity3D.isSupported(SuperSDKDataKeys.Function.SHOW_FLOAT_BUTTON))
                    {
                        PlatformSDK.GetInstance().ShowFloatButton();

                    }
                    if (SuperSDKUnity3D.isSupported(SuperSDKDataKeys.Function.SUBMIT_DATA))
                    {
                        PlatformSDK.GetInstance().SubmitData();

                    }
#elif UNITY_IOS && !NAKED
			PlatformSDK.GetInstance().IOSLoginSubmitData();
#endif
                }

                //////初始化copy数据
                StaticData.InitCopyData();
                Chat.ChatManager.Instance.ConnectionChat();

                CSShopProductList msgShop = new CSShopProductList();
                msgShop.shopType = 1;
                NetAPI.SendHttp(OpDefine.CSShopProductList, msgShop, ShopProductListCallBack);
            }
            else
            {
                DoFail("CSChangeNameTimes", OpDefine.CSChangeNameTimes);
            }
        }
        void ShopProductListCallBack(NetWork.Packets.Packet packet, bool bSuccess)
        {
            if (bSuccess)
            {
                SCShopProductList msg = packet.kBody as SCShopProductList;
                StaticData.playerData.UpdateItemShopProducts(msg.shopItemList);

                CSCookingLevel clmsg = new CSCookingLevel();

                NetAPI.SendHttp(OpDefine.CSCookingLevel, clmsg, CLCallback);


            }
            else
            {
                DoFail("CSShopProductList", OpDefine.CSShopProductList);
            }
        }



        void CLCallback(NetWork.Packets.Packet packet, bool bSuccess)
        {
            if (bSuccess)
            {
                SCCookingLevel sccl = packet.kBody as SCCookingLevel;
                StaticData.playerData.cookingLevel = sccl.level;
                StaticData.playerData.cookingExp = sccl.exp;
                StaticData.playerData.smeltLevel = sccl.gemLevel;
                StaticData.playerData.smeltExp = sccl.gemExp;
                StaticData.playerData.UpdateLifeSkills(sccl.skills);

                if (GameConfig.Instance.IsAssetFull)
                {
                    CSBigClientReward msg0 = new CSBigClientReward();
                    msg0.type = 1;
                    NetAPI.SendHttp(OpDefine.CSBigClientReward, msg0, AssetCheckCallback);
                }
                else
                {
                    QuestStory();
                }
            }
            else
            {
                DoFail("CSCookingLevel", OpDefine.CSCookingLevel);
            }
        }

        void AssetCheckCallback(NetWork.Packets.Packet pack, bool ok)
        {
            if (ok)
            {
                QuestStory();
            }
            else
            {
                DoFail("CSBigClientReward", OpDefine.CSBigClientReward);
            }
        }

        void QuestStory()
        {
            var msgQuestStory = new CSQuestList();
            NetAPI.SendHttp(OpDefine.CSQuestList, msgQuestStory, QuestStoryCallBack);
        }

        void QuestStoryCallBack(NetWork.Packets.Packet packet, bool bSuccess)
        {
            if (bSuccess)
            {
                SCQuestList msg = packet.kBody as SCQuestList;
                //StaticData.storyStep = msg.storyId;

                StaticData.storyData.Init(msg.questList);

                CSRedPoint redMsg = new CSRedPoint();
                NetAPI.SendHttp(OpDefine.CSRedPoint, redMsg, RedPointCallBack);
            }
            else
            {
                DoFail("CSQuestList",OpDefine.CSQuestList);
            }
        }



        void RedPointCallBack(NetWork.Packets.Packet packet, bool bSuccess)
        {
            if (bSuccess)
            {
                Debug.Log("redCallBack");
                SCRedPoint _msg = packet.kBody as SCRedPoint;
                StaticData.redTips.ReceiveMsg(_msg.redPointList);
                StaticData.redTips.AddHander();

                //StaticData.funcNavKit.RegistNetHandler();
                //NetAPI.SendHttp(OpDefine.CSNavigationItem, new CSNavigationItem(), FuncNavCallback);
                NetAPI.SendHttp(OpDefine.CSKVInfo, new CSKVInfo(), KVInfoCallBack);
            }
            else
            {
                DoFail("CSRedPoint", OpDefine.CSRedPoint);
            }
        }
        

        void KVInfoCallBack(NetWork.Packets.Packet packet, bool bSuccess)
        {
            if(bSuccess)
            {
                Debug.Log("KVInfoCallBack");

                SCKVInfo msg = packet.kBody as SCKVInfo;
                var dict = CommonMethod.ParseKeyValueEntry(msg.entry);
                if(dict.ContainsKey("luxuryEquipmentKey"))
                {
                    if(!string.IsNullOrEmpty(dict["luxuryEquipmentKey"]))
                    {
                        var split = dict["luxuryEquipmentKey"].Split(',');
                        foreach(var id in split)
                        {
                            StaticData.listOpenedLuxuryEquipActivity.Add(int.Parse(id));
                        }
                    }
                }

                CSFriendBlackList cfbl = new CSFriendBlackList();
                NetAPI.SendHttp(OpDefine.CSFriendBlackList, cfbl, BlackList);
            }
            else
            {
                DoFail("CSKVInfo",OpDefine.CSKVInfo);
            }
        }

        public void BlackList(NetWork.Packets.Packet packet, bool bSuccess)
        {
            if (bSuccess)
            {
                SCFriendBlackList msg = packet.kBody as SCFriendBlackList;
                StaticData.RefreshBlackList(msg.blackList);
                NetAPI.SendHttp(OpDefine.CSGetUnionAddBaseProp, new CSGetUnionAddBaseProp(), GetUnionAttribute);
            }
            else
            {
                DoFail("CSFriendBlackList", OpDefine.CSFriendBlackList);
            }
        }
        public void GetUnionAttribute(NetWork.Packets.Packet packet, bool bSuccess)
        {

            if(bSuccess)
            {
                SCGetUnionAddBaseProp result = packet.kBody as SCGetUnionAddBaseProp;
                StaticData.GetUnionAttribute(result.unionAddBaseProp);
                StaticData.SetUnionChurchAttribute(result.unionPrayProp);
                NetAPI.SendHttp(OpDefine.CSNavigationItem, new CSNavigationItem(), FuncNavCallback);
            }
            else
            {
                DoFail("CSGetUnionAddBaseProp", OpDefine.CSGetUnionAddBaseProp);
            }
        }

        void FuncNavCallback(NetWork.Packets.Packet packet, bool bSuccess)
        {
            if (bSuccess)
            {
                StaticData.funcNavKit.FuncNavCallback(packet, bSuccess);
                StaticData.funcNavKit.RegistNetHandler();
                CSChatCache msg = new CSChatCache();
                NetAPI.SendHttp(OpDefine.CSChatCache, msg, ChatMessageCallback);
            }
            else
            {
                DoFail("CSNavigationItem", OpDefine.CSNavigationItem);
            }
        }

        public void ChatMessageCallback(NetWork.Packets.Packet packet, bool bSuccess)
        {
            if (bSuccess)
            {
              
                Chat.ChatManager.Instance.ReceiveChat(((SCChatCache)packet.kBody).chatList);
                NetAPI.ConnectSocket(StaticData.socketIp, StaticData.socketPort);
                DataMessageTool.AddHandler(DataMessage.NET_CONNECT_COMPLETE, SocketConnectCallback);

            }
            else
            {
                DoFail("CSChatCache",OpDefine.CSChatCache);
            }
        }

    


        public void SocketConnectCallback(object sender)
        {
            //LoginManager.isNetFlag = true;

            DataMessageTool.RemoveHandler(DataMessage.NET_CONNECT_COMPLETE, SocketConnectCallback);
            NetAPI.RegistSocketHandler(OpDefine.SCLoginScene, SCLoginScene);
            NetAPI.RegistSocketHandler(OpDefine.SCAddTitle, SCAddTitleList);
            NetAPI.SendSocket(OpDefine.CSLoginScene, new CSLoginScene());
        }



        void SCLoginScene(object obj)
        {
            Debug.Log("<color=yellow>log scene call back</color>");
            SCLoginScene pos = (SCLoginScene)obj;
            LoginManager.willLoginScene = pos.self.position.scene;
            LoginManager.isNetFlag = true;
            #if UNITY_IOS
            if(PushMsgManger.Instance != null)
            {
                PushMsgManger.Instance.InitRegisterForNotifications();
            }
            #endif
        }

        void SCAddTitleList(object obj)
        {
            SCAddTitle titlemsg = (SCAddTitle)obj;
            if (StaticData.playerData != null)
            {
                StaticData.playerData.AddPlayerTitle(titlemsg.title);
                
            }
        }

        public override void Leave()
        {
            base.Leave();

        }
        public override void Update()
        {
            base.Update();
            if (LoginManager.isNetFlag && !LoginUI.firstCoroutine)
            {
                LoginUI.firstCoroutine = true;
                LoginManager.isNetFlag = false;
                manager.LoginDone();
            }
        }
        
        
        void DoFail(string errMsg,int code)
        {
            Debug.LogError("[DEBUG] Login fail [" + errMsg+"]");
            BoxManager.CreateOneDelMsgBox(LanguageTool.GetTextNoUpdate(1060) + " {error code [" + code + "]|", ()=> {
                GameObject.Destroy(manager.gameObject);
                ManagerController.Instance.BackToLogin();
            });
            StaticData.isLogining = false;
        }
    }
}
